package scatter.scatterserverresource.rest.componentimpl.authority;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import scatter.common.rest.tools.InterfaceTool;
import scatter.func.pojo.po.Func;
import scatter.func.rest.login.FuncLoginService;
import scatter.func.rest.service.IFuncService;
import scatter.identifier.rest.login.UserAuthorityService;
import scatter.role.pojo.po.Role;
import scatter.role.pojo.po.RoleFuncRel;
import scatter.role.rest.service.IRoleFuncRelService;
import scatter.role.rest.service.IRoleService;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 获取用户角色
 * Created by yangwei
 * Created at 2022-01-29 10:21:03
 */
@Component
public class ServerResourceUserAuthorityServiceImpl implements UserAuthorityService, FuncLoginService, InterfaceTool {
    @Autowired
    private IRoleService iRoleService;

    @Autowired
    private IFuncService iFuncService;

    @Autowired
    private IRoleFuncRelService iRoleFuncRelService;

    @Override
    public List<String> retrieveUserAuthoritiesByUserId(String userId) {
        return Optional.ofNullable(iRoleService.getByUserId(userId,false)).orElse(new ArrayList<>()).stream().map(Role::getCode).collect(Collectors.toList());
    }

    @Override
    public List<Func> retrieveFuncsByUserId(String userId) {
        List<Role> byUserId = iRoleService.getByUserId(userId,false);
        if (isEmpty(byUserId)) {
            return null;
        }
        List<RoleFuncRel> byRoleIds = iRoleFuncRelService.getByRoleIds(byUserId.stream().map(Role::getId).collect(Collectors.toList()));
        if (isEmpty(byRoleIds)) {
            return null;
        }
        List<String> funcIds = byRoleIds.stream().map(RoleFuncRel::getRoleId).collect(Collectors.toList());
        if (isEmpty(funcIds)) {
            return null;
        }
        return iFuncService.list(Wrappers.<Func>lambdaQuery().in(Func::getId, funcIds).eq(Func::getIsDisabled, false));
    }
}
